#!/usr/bin/python
'''
/*
 * This computer program is the confidential information and proprietary trade
 * secret of VistaraIT LLC.  Possessions and use of this program must  conform
 * strictly to the license agreement between the user and VistaraIT LLC.,  and
 * receipt or possession does not convey any rights to divulge, reproduce,  or
 * allow others to use this program without specific written authorization  of
 * VistaraIT LLC.
 * 
 * Copyright (c) 2014 VistaraIT, Inc. All rights reserved.
 */
'''

from django.views.generic.simple import direct_to_template
from appliance.commons import executeCommand, processTemplateTOFile
from appliance import logger
import appliance.applicationproperties as properties
import  random, os, base64


def resetPwd(request):
    response={}
    response['code'] = 1
    result = False
    reqIP = request.META['REMOTE_ADDR']
    if reqIP == '127.0.0.1':
        logger.logMessage(logger.INFO, 'Reset Password', "Received reset password request from Support site.")
        result = executeCommand(properties.APPLIANCE_RST_PWD_COMMAND, [], True)[0] == 0
    else:
        logger.logMessage(logger.ERROR, 'Reset Password', "Failed to reset password. We received request from " + reqIP)
    if result:
        response['code'] = 0
        logger.logMessage(logger.INFO, 'Reset Password', "Reset password successful.")
    else:
        response['error'] = "Failed to reset password"
    return direct_to_template(request,'api/apiResponse.xml',{"response":response})

def changePwd(request):
    response={}
    response['code'] = 1
    result = False
    reqIP = request.META['REMOTE_ADDR']
    if reqIP == '127.0.0.1':
        xmlData = request.raw_post_data
        logger.logMessage(logger.INFO, 'Change Password', "Received change password request from Support site." + xmlData)
        instance = xen.xm.getRequestConfig(xmlData)
        username = instance['username']
        password = instance['password']
        if username != "" and password == "":
            result = executeCommand(properties.APPLIANCE_RST_PWD_COMMAND, [username], True)[0] == 0
        elif username == "" and password == "":
            result = executeCommand(properties.APPLIANCE_RST_PWD_COMMAND, [], True)[0] == 0
        elif username != "" and password != "":
            password = password.replace('$','\$')
            result = executeCommand(properties.APPLIANCE_RST_PWD_COMMAND, [username,password], True)[0] == 0
    else:
        logger.logMessage(logger.ERROR, 'Change Password', "Failed to change password. We received request from " + reqIP)
    if result:
        response['code'] = 0
        logger.logMessage(logger.INFO, 'Change Password', "Changed password successfully.")
    else:
        response['error'] = "Failed to change password for " + username
    return direct_to_template(request,'api/apiResponse.xml',{"response":response})

def deregisterAppliance(request):
    response={}
    response['code'] = 1
    reqIP = request.META['REMOTE_ADDR']
    if reqIP == '127.0.0.1':
        logger.logMessage(logger.INFO, 'De-register Appliance', "Received de-register request from Support site.")
        response['code'] = 0
        os.system("/usr/bin/sudo /usr/bin/python /home/admin/adminui/applianceInfoCmdline.py -s deregisterAppliance &")
        return direct_to_template(request,'api/apiResponse.xml',{"response":response})
    else:
        logger.logMessage(logger.ERROR, 'De-register Appliance', "Failed to de-register appliance. We received request from " + reqIP)
        response['error'] = "Failed to reset the appliance to factory default"
        return direct_to_template(request,'api/apiResponse.xml',{"response":response})

def rebootAppliance(request):
    response={}
    response['code'] = 1
    reqIP = request.META['REMOTE_ADDR']
    if reqIP == '127.0.0.1':
        logger.logMessage(logger.INFO, 'Reboot Appliance', "Received reboot appliance request from Support site.")
        response['code'] = 0
        #executeCommand("/usr/bin/sudo /sbin/reboot \&", [], True)
        os.system("/usr/bin/sudo /sbin/reboot &")
        return direct_to_template(request,'api/apiResponse.xml',{"response":response})
    else:
        logger.logMessage(logger.ERROR, 'Reboot Appliance', "Failed to reboot appliance. We received request from " + reqIP)
        response['error'] = "Failed to reboot appliance"
        return direct_to_template(request,'api/apiResponse.xml',{"response":response})

def callCheckUpdates(request):
    response={}
    response['code'] = 1
    reqIP = request.META['REMOTE_ADDR']
    if reqIP == '127.0.0.1':
        logger.logMessage(logger.INFO, 'Check updates', "Received force update request from Support site.")
        response['code'] = 0
        os.system("/usr/bin/sudo /usr/bin/python /var/fw/callCheckUpdates.py &")
        return direct_to_template(request,'api/apiResponse.xml',{"response":response})
    else:
        logger.logMessage(logger.ERROR, 'Check Updates', "Failed to initiate update request for appliance. We received request from " + reqIP)
        response['error'] = "Failed to initiate updates request"
        return direct_to_template(request,'api/apiResponse.xml',{"response":response})

def disconnectTunnel(request):
    response={}
    response['code'] = 1
    reqIP = request.META['REMOTE_ADDR']
    if reqIP == '127.0.0.1':
        logger.logMessage(logger.INFO, 'Disconnect tunnel', "Received force disconnect tunnel request from Support site.")
        response['code'] = 0
        os.system("/usr/bin/sudo /usr/bin/python /home/admin/adminui/applianceInfoCmdline.py -a disconnectTunnel &")
        return direct_to_template(request,'api/apiResponse.xml',{"response":response})
    else:
        logger.logMessage(logger.ERROR, 'Disconnect tunnel', "Failed to initiate disconnect tunnel request for appliance. We received request from " + reqIP)
        response['error'] = "Failed to initiate disconnect tunnel request"
        return direct_to_template(request,'api/apiResponse.xml',{"response":response})
    
'''
def installLicense(request):
    response={}
    response['code'] = 1
    reqIP = request.META['REMOTE_ADDR']

    appmanager = ApplianceManager()
    if reqIP == '127.0.0.1':
        logger.logMessage(logger.INFO, 'Install License', "Received install license request from Support site.")
        appmanager.cfgmanager.saveLicenseReachability()
        if appmanager.installLicense():
            response['code'] = 0

        return direct_to_template(request,'api/apiResponse.xml',{"response":response})
    else:
        logger.logMessage(logger.ERROR, 'Install License', "Failed to install license. We received request from " + reqIP)
        response['error'] = "Failed to install license"
        return direct_to_template(request,'api/apiResponse.xml',{"response":response})
'''
   
def getAssetInfo(request):
    response={}
    response['code'] = 1
    reqIP = request.META['REMOTE_ADDR']

    if reqIP == '127.0.0.1':
        logger.logMessage(logger.INFO, 'Get Asset Info', "Received get asset info request from Support site.")
        response['code'] = 0
        os.system("/usr/bin/perl /nems/nagios/libexec/get_asset_info.pl &")
        return direct_to_template(request,'api/apiResponse.xml',{"response":response})
    else:
        logger.logMessage(logger.ERROR, 'Get Asset Info', "Failed to initiate get asset info request for appliance. We received request from " + reqIP)
        response['error'] = "Failed to initiate get asset info request"
        return direct_to_template(request,'api/apiResponse.xml',{"response":response})

def getMonitoringConfigs(request):
    response={}
    response['code'] = 1
    reqIP = request.META['REMOTE_ADDR']

    if reqIP == '127.0.0.1':
        logger.logMessage(logger.INFO, 'Get Monitoring Configs', "Received monitoring configs request from Support site.")
        try:
            result = executeCommand("/usr/bin/sudo /usr/bin/perl /nems/nagios/clientcode/getConfigs.pl -f 0", [], True)[0] == 0
            cfile = open('/nems/nagios/clientcode/configResult.txt', 'r')
            output = cfile.read()
            cfile.close()
            output = output.strip()
            if result and output == 'Configs Applied Successfully':
                response['code'] = 0
                response['result'] = output
            else:
                response['error'] = output
        except Exception, msg:
            response['error'] = str(msg)
        return direct_to_template(request, 'api/apiResponse.xml', {"response": response})
    else:
        logger.logMessage(logger.ERROR, 'Get Monitoring Configs', "Failed to get monitoring configs from Support site. We received request from " + reqIP)
        response['error'] = "Failed to initiate get monitoring configs request"
        return direct_to_template(request, 'api/apiResponse.xml', {"response": response})

def onDemandServiceChecks(request):
    response={}
    response['code'] = 1
    reqIP = request.META['REMOTE_ADDR']
    
    if reqIP == '127.0.0.1':
        logger.logMessage(logger.INFO, 'On-demand Service Checks', "Received On-demand Service Checks request from Support site.")
        try:
            xmlData = request.raw_post_data
            tmpDir = "/etc/nsg/tmp"
            tmpFile = tmpDir + '/currentValues.xml'
            if not os.path.exists(tmpDir):
                executeCommand("/usr/bin/sudo /bin/mkdir -p " + tmpDir, [], True)
            executeCommand("/usr/bin/sudo /bin/touch " + tmpFile, [], True)
            cmd1 = "/usr/bin/sudo chown admin.admin " + tmpFile + " >/dev/null 2>&1"    
            executeCommand(cmd1, [], True)
            cmd2 = "/usr/bin/sudo chmod 644 " + tmpFile + " >/dev/null 2>&1"    
            executeCommand(cmd2, [], True)

            cfile = open(tmpFile, 'wb')
            cfile.write(xmlData)
            cfile.close()

            result = executeCommand("/usr/bin/sudo /usr/bin/perl /nems/nagios/clientcode/getCurrentValues.pl -f " + tmpFile, [], True)
            if result[0] == 0:
                response['code'] = 0
                response['result'] =  base64.b64encode(result[1])
            else:
                response['error'] =  base64.b64encode(result[1])
        except Exception, msg:
            logger.logMessage(logger.ERROR, 'On-demand Service Checks Exc', str(msg))
            response['error'] = str(msg)
        return direct_to_template(request, 'api/apiResponse.xml', {"response": response})
    else:
        logger.logMessage(logger.ERROR, 'On-demand Service Checks', "Failed to get On-demand service check request. We received request from " + reqIP)
        response['error'] = "Failed to get On-demand service check request"
        return direct_to_template(request, 'api/apiResponse.xml', {"response": response})
